<template>
  <div class="apply-dialog">
    <el-dialog
      title=""
      :visible.sync="dialogVisible"
      :fullscreen="true"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <LimitTech ref="LimitTech" @showTech="openTech" />
      <Tech ref="Tech" @showLimit="openHelp" />
      <div slot="title" class="flex flex-row align-center justify-content-end">
        <div class="btn-list flex flex-row align-center">
          <el-button
            type="warning"
            size="mini"
            :disabled="draftDisabled"
            @click="draftAction"
          >
            暂存
          </el-button>

          <!--          <el-button
            type="warning"
            size="mini"
            :disabled="recallDisabled"
            @click="recallOrder()"
          >
            撤回
          </el-button>-->
          <el-button
            type="primary"
            size="mini"
            :disabled="submitDisabled"
            @click="submitAction"
          >
            提交
          </el-button>
          <!-- <el-button type="primary" size="mini" @click="handlePrint(printData)">
            导出PDF
          </el-button> -->

          <!--          <div class="pl15 pr15">
            上报人：<span class="primary-color">{{ name }}</span>
          </div>
          <div class="pl15 pr15">
            最新状态：<span v-if="auditStatus == 1" class="primary-color">{{
              orderState
            }}</span>
            <span v-else class="danger-color">已撤回申请</span>
          </div>-->
          <div class="ml50" @click="handleClose">
            <i class="el-icon-close cursor-p font22 line-height-32" />
          </div>
        </div>
      </div>
      <div id="pdfHtml" class="app-container">
        <el-card
          class="box-card apply-box mt10 mb20"
        >
          <div slot="header" class="clearfix flex flex-row align-center">
            <div class="line" />
            <span class="font18 ml10 flex-auto">申报者填写</span>
            <el-button
              id="no-print"
              type="danger"
              round
              icon="el-icon-thumb"
              size="small"
              @click="openHelp"
            >申报指引</el-button>
          </div>

          <el-form
            ref="generateForm"
            label-suffix=":"
            size="small"
            :model="models"
            :rules="rules"
            label-position="right"
            label-width="180px"
          >
            <el-row
              type="flex"
              :gutter="30"
              justify="start"
              align="top"
            >
              <el-col
                :span="8"
              >
                <el-form-item
                  label="项目名称"
                  prop="name"
                  label-width="130px"
                >
                  <el-input
                    v-model="models.name"
                    :style="{width:'100%'}"
                    placeholder="请输入项目名称"
                  />
                </el-form-item>
              </el-col>
              <el-col
                :span="8"
              >
                <el-form-item
                  label="项目编号"
                  prop="projectNo"
                >
                  <el-input
                    v-model="models.projectNo"
                    :style="{width:'100%'}"
                    placeholder="请输入项目编号"
                    disabled
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row
              type="flex"
              :gutter="30"
              justify="start"
              align="top"
            >
              <el-col
                :span="8"
              >
                <el-form-item
                  label="项目分类"
                  prop="projectClass"
                  label-width="130px"
                >
                  <el-select
                    v-model="models.projectClass"
                    :style="{width:'100%'}"
                    placeholder="请选择项目分类"
                    :filterable="false"
                    clearable
                    value=""
                  >
                    <el-option
                      v-for="(item, index) in [{label:'非限制',value:1},{label:'限制类',value:2}]"
                      :key="index"
                      :value="item.value"
                      :label="item.label"
                    />

                  </el-select>
                </el-form-item>
              </el-col>
              <el-col
                :span="8"
              >
                <el-form-item
                  label="申请科室"
                  prop="applyDeptId"
                >
                  <el-select
                    v-model="models.applyDeptId"
                    :style="{width:'100%'}"
                    placeholder="请选择科室"
                    filterable
                    clearable
                    value=""
                    @change="handleChange"
                  >
                    <el-option
                      v-for="(item, index) in structureList"
                      :key="item.id"
                      :value="item.id"
                      :label="item.depName"
                    />

                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row
              type="flex"
              :gutter="30"
              justify="start"
              align="top"
            >
              <!-- <el-col
                :span="8"
              >
                <el-form-item
                  label="技术类别"
                  prop="techType"
                  label-width="130px"
                >
                  <el-select
                    v-model="models.techType"
                    :style="{width:'100%'}"
                    placeholder="请选择项目分类"
                    :filterable="false"
                    clearable
                    value=""
                  >
                    <el-option
                      v-for="(item, index) in [{label:'手术操作',value:1},{label:'检验检查',value:2},{label:'其他治疗技术',value:3}]"
                      :key="index"
                      :value="item.value"
                      :label="item.label"
                    />

                  </el-select>
                </el-form-item>
              </el-col>
              <el-col
                :span="8"
              > -->
              <el-col :span="8">
                <el-form-item label="技术类别" prop="techType" label-width="130px">
                  <el-cascader
                    v-model="techTypeArr"
                    :options="categoryCatalog"
                    :style="{ width: '100%' }"
                    placeholder="请选择技术类别"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="项目负责人"
                  prop="applyManagerName"
                >
                  <el-input
                    v-model="models.applyManagerName"
                    :style="{width:'100%'}"
                    placeholder="请输入项目负责人"
                    
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row
              type="flex"
              :gutter="30"
              justify="start"
              align="top"
            >
              <!-- <el-col
                :span="8"
              >
                <el-form-item
                  label="负责人工号"
                  prop="projectManagerEmp"
                  label-width="130px"
                >
                  <el-input
                    v-model="models.projectManagerEmp"
                    :style="{width:'100%'}"
                    placeholder="请输入负责人工号"
                  />
                </el-form-item>
              </el-col> -->
              <el-col
                :span="8"
              >
                <el-form-item
                  label="负责人联系方式"
                  prop="projectManagerContact"
                    
                >
                  <el-input
                    v-model="models.projectManagerContact"
                    :style="{width:'100%'}"
                    placeholder="请输入负责人联系方式"
                  />
                </el-form-item>
              </el-col>
              <el-col
                :span="8"
              >
                <el-form-item
                  label="目标例数"
                  prop="targetNumber"
                >
                  <el-input
                    v-model="models.targetNumber"
                    :style="{width:'100%'}"
                    placeholder="请输入目标例数"
                    type="number"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row
              type="flex"
              :gutter="30"
              justify="start"
              align="top"
            >
              <el-col
                :span="8"
              >
                <el-form-item
                  label="项目成员"
                  prop="projectMember"
                  label-width="130px"
                >
                  <div class="member-input-container">
                    <el-input
                      v-model="selectedMemberText"
                      placeholder="请选择项目成员"
                      readonly
                      type="textarea"
                      :rows="4"
                      :style="{ width: '100%' }"
                      @click.native="openMemberDialog"
                    >
                      <el-button slot="append" icon="el-icon-user" @click="openMemberDialog">选择</el-button>
                    </el-input>
                  </div>
                </el-form-item>
              </el-col>
                <el-col
                :span="8"
              >
                <el-form-item
                  label="填报人姓名"
                  prop="applyUserName"
                >
                  <el-input
                    v-model="models.applyUserName"
                    :style="{width:'100%'}"
                    placeholder="请输入填报人姓名"
                    disabled
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row
              type="flex"
              :gutter="30"
              justify="start"
              align="top"
            >
              <el-col
                :span="8"
              >
                <el-form-item
                  label="填报人工号"
                  prop="workNumber"
                   label-width="130px"
                >
                  <el-input
                    v-model="models.workNumber"
                    :style="{width:'100%'}"
                    placeholder="请输入工号"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col
                :span="8"
              >
                <el-form-item
                  label="填报时间"
                  prop="fillTime"
                >
                  <el-input
                    v-model="models.fillTime"
                    :style="{width:'100%'}"
                    placeholder="请输入项目名称"
                    disabled
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row
              type="flex"
              :gutter="30"
              justify="start"
              align="top"
            >
              <el-col
                :span="16"
              >
                <el-form-item
                  label="设备名称"
                  prop="deviceNames"
                  label-width="130px"
                >
                  <el-input
                    type="textarea"
                    :rows="3"
                    placeholder="请输入设备名称"
                    v-model="models.deviceNames"
                    :style="{ width: '62%' }"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row
              type="flex"
              :gutter="30"
              justify="start"
              align="top"
            >
              
              <!-- <el-col
                :span="8"
              >
                <el-form-item
                  label="设备或试剂"
                  prop="equipmentReagentsExist"
                >
                  <el-radio-group
                    v-model="models.equipmentReagentsExist"
                    :style="{ width: 130 }"
                  >
                    <el-radio
                      v-for="(item, index) in [{label:'有',value:1},{label:'无',value:0}]"
                      :key="index"
                      class="incat-radio incat-mini"
                      :style="{display: 'inline-block'}"
                      :label="item.value"
                    >
                      <template>{{ item.label }}</template>
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col> -->
            </el-row>
            
            <!-- <el-row
              type="flex"
              :gutter="30"
              justify="start"
              align="top"
            >
              <el-col
                :span="16"
              >
                <el-form-item
                  label="备注"
                  prop="remark"
                  label-width="130px"
                >
                  <el-input
                    v-model="models.remark"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入项目名称"
                    :style="{ width: '62%' }"
                  />
                </el-form-item>
              </el-col>
            </el-row> -->
            <el-row
              type="flex"
              :gutter="30"
              justify="start"
              align="top"
            >
              <el-col
                :span="16"
              >
                <el-form-item
                  label="申请书"
                  prop="applyDocs"
                  label-width="130px"
                >
                  <FileUpload :element="uploadConfig" :preview="false" @fileList="fileList" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <!-- <el-row
              type="flex"
              :gutter="30"
              justify="start"
              align="top"
            >
              <el-col
                :span="16"
              >
                <el-form-item
                  label="设备三证"
                  prop="deviceDocs"
                  label-width="130px"
                >
                  <FileUpload :element="uploadConfig" :preview="false" @fileList="fileList1" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row
              type="flex"
              :gutter="30"
              justify="start"
              align="top"
            >
              <el-col
                :span="16"
              >
                <el-form-item
                  label="设备三证为"
                  label-width="130px"
                >
                  <span>*</span>
                  <span style="font-size: 15px;font-weight: 400;color:#606266">
                    《医疗器械生产企业许可证》、《医疗器械注册证》和《医疗器械经营企业许可证》。
                  </span>
                </el-form-item>
              </el-col>
            </el-row> -->
            <el-row
              type="flex"
              :gutter="30"
              justify="start"
              align="top"
            >
              <el-col
                :span="16"
              >
                <el-form-item
                  label="补充资料"
                  prop="additionalDocs"
                  label-width="130px"
                >
                  <FileUpload :element="uploadConfig" :preview="false" @fileList="fileList2" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row
              type="flex"
              :gutter="30"
              justify="start"
              align="top"
            >
              <el-col
                :span="16"
              >
                <el-form-item
                  label="补充资料说明"
                  label-width="130px"
                >
                  <div>
                    <span>*</span>
                    <span style="font-size: 15px;font-weight: 400;color:#606266">
                      如有培训证明，请上传
                    </span>
                  </div>
                  <!-- <div>
                    <span>*</span>
                    <span style="font-size: 15px;font-weight: 400;color:#606266">
                      如属本市首次开展的医疗技术，需上传第三方评价机构出具的确认需纳入本市限制类技术目录的评估报告
                    </span>
                  </div> -->
                  <div>
                    <span>*</span>
                    <span style="font-size: 15px;font-weight: 400;color:#606266">
                      其他申请所需材料也可上传为补充资料
                    </span>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>
    </el-dialog>
    <LeaderDialog ref="leaderRef" @selectLeader="selectLeader" />
    <el-dialog
      title="添加项目成员"
      :visible.sync="memberDialogVisible"
      width="50%"
      :close-on-click-modal="false"
      append-to-body
    >
      <div class="member-dialog-content">
        <!-- 搜索框 -->
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入关键字搜索"
            prefix-icon="el-icon-search"
            clearable
            @input="handleSearch"
          />
        </div>
        <!-- 部门树形选择 -->
        <div class="tree-container">
          <el-tree
            ref="memberTree"
            :data="departmentUserOptions"
            :props="{
              label: 'name',
              children: 'children'
            }"
            show-checkbox
            node-key="id"
            default-expand-all
            :filter-node-method="filterNode"
            @check="handleTreeCheck"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ data.name }}</span>
              <span v-if="data.empNo">({{ data.empNo }})</span>
            </span>
          </el-tree>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelMemberSelect">取 消</el-button>
        <el-button type="primary" @click="confirmMemberSelect">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Vue from 'vue'
import { GenerateForm } from '@/components/VueFormMaking'
import FileUpload from '@/components/VueFormMaking/components/Upload/file.vue'
import 'form-making/dist/FormMaking.css'
Vue.component(GenerateForm.name, GenerateForm)
import LimitTech from './limitTech/index.vue'
import LeaderDialog from './leader/index.vue'

import Tech from './tech/index.vue'
import {
  processStructure,
  createWorkOrder,
  updateWorkOrder,
  draftWorkOrder,
  recallWorkOrder,
  newCreateWorkOrder,
  newDoUpdate,
  selectProjectNumbera
} from '@/api/xjs/work-order'
import { listAllUser, newListUser } from '@/api/system/sysuser'
import { getOrdinaryDeptList, newTreeselect, newGetUserList, getNewDeptList, getNewDeptInfo } from '@/api/system/dept'
import { mapGetters } from 'vuex'
import printJS from 'print-js'
import moment from 'moment'
import { Loading } from 'element-ui'
import { newGetUserInfo } from '@/api/user'
export default {
  name: 'ApplyDialog',
  components: {
    FileUpload,
    LimitTech,
    Tech,
    LeaderDialog
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    listData: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      models: {
        projectMember: [],
        applyUserName: '',
        workNumber: '',
        fillTime: moment().format('YYYY-MM-DD HH:mm:ss'),
        name: '',
        projectNo: '',
        projectClass: '',
        applyDeptId: '',
        techType: '',
        applyManagerName: '',
        projectManagerContact: '',
        targetNumber: '',
        deviceNames: '',
        applyDocs: '',
        additionalDocs: ''
      },
      allUsers: [],
      displayUserGroups: [],
      departmentUserOptions: [],
      structureList: [],
      selectedMemberNames: [],
      selectedMemberText: '',
      memberDialogVisible: false,
      dialogVisible: false,
      techTypeArr: [],
      searchKeyword: '',
      tempSelectedMembers: [],
      tempSelectedNames: [],
      originalSelectedMembers: [],
      originalSelectedNames: [],
      submitDisabled: false,
      draftDisabled: false,
      recallDisabled: false,
      categoryCatalog: [
        {
          value: 1,
          label: '手术操作类',
          children: [
            { value: 11, label: '一级项目（国内医院尚未开展的技术项目）' },
            { value: 12, label: '二级项目（本学科近年来发展成熟的、在国内已有医院开展、省内及本院尚未开展）' },
            { value: 13, label: '三级项目（本学科发展成熟，在国内及省内均有开展，而本院尚未开展）' },
            { value: 14, label: '四级项目（报备类项目，创新性一般，技术含量不高，仅为设备、试剂、耗材等引进或调整，在本院尚未开展的技术项目）' }
          ]
        },
        {
          value: 2,
          label: '非手术操作类',
          children: [
            { value: 21, label: '一级项目（国内医院尚未开展的技术项目）' },
            { value: 22, label: '二级项目（本学科近年来发展成熟的、在国内已有医院开展、省内及本院尚未开展）' },
            { value: 23, label: '三级项目（本学科发展成熟，在国内及省内均有开展，而本院尚未开展）' },
            { value: 24, label: '四级项目（报备类项目，创新性一般，技术含量不高，仅为设备、试剂、耗材等引进或调整，在本院尚未开展的技术项目）' }
          ]
        }
      ],
      usreMesssageList:[],
      searchPriceNo: '',
      auditStatus: 1,
      printData: {
        printable: 'printFrom',
        header: '',
        ignore: ['no-print']
      },
      workOrdeInfo: {
        id: null
      },
      uploadConfig: {
        options: {
          // action: "http://192.168.0.107:8002/api/v1/public/uploadFile?file_type=files"
          defaultValue: [],
          disabled: false,
          length: 9,
          tip: '',
          width: '30%'
        }
      },
      limitTechList: [],
      selectLimitData: [],
      loading: false,
      limitTechVisible: false,
      downloadVisible: false,
      active: 0,
      total: 0,
      structureUserList: [],
      userList: [],
      processStructureValue: {},
      queryParams: {
        pageIndex: 1,
        pageSize: 5,
        name: undefined
      },
      tpls: [],
      newTpls: [],
      ruleForm: {
        workOrderId: 0,
        title: '',
        projectNo: '',
        process: '',
        classify: '',
        state: [],
        source: '',
        source_state: '',
        process_method: '',
        tpls: {
          form_structure: [],
          form_data: []
        },
        newTpls: {},
        tasks: [],
        status: 0
      },

      rules: {
        name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        projectNo: [{ required: true, message: '请输入项目编号', trigger: 'blur' }],
        projectClass: [{ required: true, message: '请选择项目分类', trigger: 'blur' }],
        applyDeptId: [{ required: true, message: '请选择科室', trigger: 'blur' }],
        techTypeArr: [{ required: true, message: '请选择技术类型', trigger: 'blur' }],
        // equipmentReagentsExist: [{ required: true, message: '请选择设备或试剂', trigger: 'blur' }],
        // projectManagerEmp: [{ required: true, message: '请输入项目负责人工号', trigger: 'blur' }],
        projectManagerContact: [{ required: true, message: '请输入项目负责人联系方式', trigger: 'blur' }],
        targetNumber: [{ required: true, message: '请输入目标例数', trigger: 'blur' }],
        projectMember: [{ required: true, message: '请选择项目成员', trigger: 'change' }],
      },
      remoteFunc: {
        // 获取用户列表
        async userList(resolve) {
          const res = await listAllUser({})
          const options = res.data
          resolve(options)
        },
        async deptTreeList(resolve) {
          const res = await getOrdinaryDeptList()
          resolve(res.data)
        }
      },
      selectedMemberNames: [],
      memberDialogVisible: false,
      searchKeyword: '',
      selectedMemberText: '',
      tempSelectedMembers: [],
      tempSelectedNames: [],
      originalSelectedMembers: [],
      originalSelectedNames: []
    }
  },
  computed: {
    ...mapGetters(['name', 'newUserInfo', 'globalConfig']),
    orderState() {
      if (this.workOrdeInfo.id != null) {
        if (this.workOrdeInfo.status == 1) {
          return '未提交(草稿)'
        } else {
          return `${this.workOrdeInfo.current_state_name}【${
            this.workOrdeInfo.principals
          }】`
        }
      } else {
        return '未提交'
      }
    }
  },
  created() {
    console.log(11111, this.listData) 
    // 在组件创建时获取项目编号
    selectProjectNumbera().then(res => {
      console.log('项目编号接口返回:', res)
      // 直接使用返回的字符串作为项目编号
      this.models.projectNo = res
      console.log('设置项目编号:', this.models.projectNo)
    }).catch(error => {
      console.error('获取项目编号出错:', error)
      // 生成默认项目编号：当前年份 + 6位随机数
      const year = new Date().getFullYear()
      const randomNum = Math.floor(100000 + Math.random() * 900000)
      this.models.projectNo = `${year}${randomNum}`
      console.log('使用默认项目编号:', this.models.projectNo)
      this.$message.warning('系统自动生成项目编号')
    })
    // this.getNewDeptTreeList()
  },
  methods: {
    fileList(files) {
      // this.models.applyDocsTemp = files;
      this.models.applyDocs = JSON.stringify(files)
    },
    fileList1(files) {
      // this.models.deviceDocsTemp = files;
      this.models.deviceDocs = JSON.stringify(files)
    },
    fileList2(files) {
      // this.models.additionalDocsTemp = files;
      this.models.additionalDocs = JSON.stringify(files)
    },
    handleChange(v) {
      // getNewDeptInfo({ id: v }).then(res => {
      //   this.models.applyManagerName = res.records[0].deptManagerName
      // })
    },
    guitda(){
      selectProjectNumbera().then(res => {
        this.models.projectNo = res.total.toString()
      })
    },
     // 按部门分组用户
    groupAndDisplayUsers(users) {
      try {
        const deptMap = {}
        users.forEach(user => {
          if (!deptMap[user.depID]) {
            deptMap[user.depID] = {
              depID: user.depID,
              depName: user.depName || '未分配部门',
              users: []
            }
          }
          deptMap[user.depID].users.push(user)
        })

        // 部门内部按工号排序
        Object.values(deptMap).forEach(dept => {
          dept.users.sort((a, b) => (a.empNo || '').localeCompare(b.empNo || ''))
        })

        // 部门按名称排序
        this.displayUserGroups = Object.values(deptMap)
          .sort((a, b) => (a.depName || '').localeCompare(b.depName || ''))
          .filter(group => group.users.length > 0)
        
        // 构建级联选择器数据
        this.buildCascaderOptions()
      } catch (err) {
        console.error('处理用户分组数据出错:', err)
      }
    },
    
    // 构建级联选择器数据
    buildCascaderOptions() {
      try {
        this.departmentUserOptions = this.displayUserGroups.map(dept => ({
          id: dept.depID,
          name: dept.depName,
          children: dept.users.map(user => ({
            id: String(user.id),
            name: user.name,
            empNo: user.empNo,
            depName: user.depName,
            groupName: user.groupName
          }))
        }))
      } catch (err) {
        console.error('构建级联选择器数据出错:', err)
        this.departmentUserOptions = []
      }
    },
    
    // 处理成员选择变化
    handleMemberChange(value) {
      console.log('选中的成员ID:', value)
      
      // 检查是否有部门ID被选中
      const selectedDeptIds = value.filter(id => {
        // 检查是否是部门ID（在departmentUserOptions中查找）
        return this.departmentUserOptions.some(dept => dept.id === id)
      })
      
      // 如果有部门被选中，添加该部门下的所有人员
      if (selectedDeptIds.length > 0) {
        const allUserIds = new Set(value)
        
        // 遍历选中的部门，添加其下所有人员
        selectedDeptIds.forEach(deptId => {
          const dept = this.departmentUserOptions.find(d => d.id === deptId)
          if (dept && dept.children) {
            dept.children.forEach(user => {
              allUserIds.add(user.id)
            })
          }
        })
        
        // 更新选中的值
        this.models.projectMember = Array.from(allUserIds)
      } else {
        // 如果没有部门被选中，直接使用选中的值
        this.models.projectMember = value
      }
      
      // 更新选中的成员姓名
      this.selectedMemberNames = this.models.projectMember.map(id => {
        // 在所有用户中查找对应的用户
        const user = this.allUsers.find(u => u.id === id)
        return user ? user.name : ''
      }).filter(name => name) // 过滤掉空值
    },
    downLoadDoc(type) {
      var a = document.createElement('a')
      switch (type) {
        case 1:
          a.href =
            `/${this.globalConfig.folderName}/非限制类使用——${this.globalConfig.fullName}医疗技术临床应用审核申请书（操作技术）.docx`
          a.download =
            `非限制类使用——${this.globalConfig.fullName}医疗技术临床应用审核申请书（操作技术）.docx`
          break
        case 2:
          a.href =
            `/${this.globalConfig.folderName}/非限制类使用——${this.globalConfig.fullName}医疗技术临床应用审核申请书（检验检查）.docx`
          a.download =
            `非限制类使用——${this.globalConfig.fullName}医疗技术临床应用审核申请书（检验检查）.docx`
          break
        case 3:
          a.href = '/static/xjs/限制类备案使用——新技术备案申请表（样表）.docx'
          a.download = '限制类备案使用——新技术备案申请表（样表）.docx'
          break
        case 4:
          a.href = '/static/xjs/限制类备案使用——新技术备案申请表（样表）.docx'
          a.download = '限制类备案使用——新技术备案申请表（样表）.docx'
          break
        case 5:
          a.href = '/static/xjs/限制类备案使用——新技术备案申请表（样表）.docx'
          a.download = '限制类备案使用——新技术备案申请表（样表）.docx'
          break
      }
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
      a.remove()
    },
    openHelp() {
      this.$refs.Tech.close()
      this.$refs.LimitTech.open()
    },
    openTech() {
      this.$refs.LimitTech.close()
      this.$refs.Tech.open()
    },

    handlePrint(params) {
      /* printJS({
        maxWidth: 1920,
        documentTitle: '甘肃省人民医院医务一网通办',
        printable: params.printable, // 'printFrom',
        type: params.type || 'html',
        header: params.header, // '表单',
        targetStyles: ['*'],
        ignoreElements: params.ignore || [], // ['no-print']
        properties: params.properties || null
      })*/

      const vm = this
      const A4_WIDTH = 592.28
      const A4_HEIGHT = 841.89 // $myLoading 自定义等待动画组件，实现导出事件的异步等待交互
      this.pdfLoading = true
      this.loadingFull = Loading.service({
        target: document.querySelector('.app-wrapper'),
        lock: true,
        text: '正在导出中，请稍后……',
        background: 'rgba(0, 0, 0, 0.7)',
        customClass: 'zIndex9999'
      })
      vm.$nextTick(() => {
        // dom的id。
        const target = document.getElementById('pdfHtml')
        const pageHeight = target.scrollWidth / A4_WIDTH * A4_HEIGHT
        // 获取分割dom，此处为class类名为item的dom
        const lableListID = document.getElementsByClassName('item-excel')
        // 进行分割操作，当dom内容已超出a4的高度，则将该dom前插入一个空dom，把他挤下去，分割
        for (let i = 0; i < lableListID.length; i++) {
          const multiple = Math.ceil((lableListID[i].offsetTop + lableListID[i].offsetHeight / 2) / pageHeight)
          if (this.isSplit(lableListID, i, multiple * pageHeight)) {
            const divParent = lableListID[i].parentNode
            // 获取该div的父节点
            const newNode = document.createElement('div')
            newNode.className = 'emptyDiv'
            newNode.style.background = '#ffffff'
            const _H = multiple * pageHeight - (lableListID[i].offsetTop + lableListID[i].offsetHeight)
            newNode.style.height = _H + 30 + 'px'
            newNode.style.width = '100%'
            const next = lableListID[i].nextSibling
            // 获取div的下一个兄弟节点
            // // 判断兄弟节点是否存在
            if (next) {
              // 存在则将新节点插入到div的下一个兄弟节点之前，即div之后
              divParent.insertBefore(newNode, next)
            } else {
              // 不存在则直接添加到最后,appendChild默认添加到divParent的最后
              divParent.appendChild(newNode)
            }
          }
        }
        // 传入title和dom标签，此处是 #content// 异步函数，导出成功后处理交互
        this.getPdf(`${this.models.name || '未知项目'}`, '#pdfHtml').then(() => {}).catch(() => {})
        setTimeout(() => {
          this.loadingFull.close()
          this.pdfLoading = false
        }, 2000)
        this.pdfLoading = false
      })
    },
    handleClose() {
      this.$refs['generateForm'].clearValidate()
      this.dialogVisible = false
      this.resetData()
      this.$emit('refreshTable')
    },
    open(row) {
      try {
        // 重置所有数据
        this.resetData()
        
        console.log('开始打开编辑对话框，传入数据:', row)

        // 获取项目编号
        this.guitda()

        // 保存原始数据的副本
        const originalData = row ? { ...row } : {}
        console.log('处理的原始数据:', originalData)

        // 首先加载用户列表
        const loadUserList = async () => {
          try {
            const res = await newListUser({
              currentPage: 1,
              pageSize: 10000,
              empNo: null,
              deptID: "",
              userID: "",
              userName: ""
            })

            if (res.records) {
              // 过滤有效用户数据
              this.allUsers = res.records.filter(user => 
                user.vldFG === '0' && user.name && user.empNo
              )
              console.log('加载的用户列表数量:', this.allUsers.length)
              
              // 初始化部门用户数据
              this.groupAndDisplayUsers(this.allUsers)
              return true
            } else {
              throw new Error('获取用户列表返回数据无效')
            }
          } catch (err) {
            console.error('加载用户列表失败:', err)
            this.$message.error('加载用户列表失败')
            return false
          }
        }

        // 使用 Promise.all 同时加载所需数据
        Promise.all([
          newGetUserInfo().catch(err => {
            console.error('获取用户信息失败:', err)
            return { records: [{ name: '', empNo: '' }] }
          }),
          getNewDeptList({ pageSize: 9999 }).catch(err => {
            console.error('获取部门列表失败:', err)
            return { records: [] }
          }),
          loadUserList()
        ]).then(([userInfoData, deptData]) => {
          // 设置基本信息
          if (userInfoData.records && userInfoData.records[0]) {
            this.models.applyUserName = userInfoData.records[0].name
            this.models.workNumber = userInfoData.records[0].empNo
          }

          // 设置部门列表
          if (deptData.records) {
            this.structureList = deptData.records
          }

          // 处理编辑数据
          if (originalData && Object.keys(originalData).length > 0) {
            // 合并原始数据到 models，但保留已设置的基本信息
            this.models = {
              ...this.models,
              ...originalData,
              applyUserName: this.models.applyUserName,
              workNumber: this.models.workNumber
            }

            // 处理技术类别
            if (originalData.techType) {
              try {
                this.techTypeArr = originalData.techType.split(',').map(Number)
              } catch (err) {
                console.error('处理技术类别数据失败:', err)
                this.techTypeArr = []
              }
            }

            // 处理项目成员
            if (originalData.projectMember) {
              try {
                const memberIds = originalData.projectMember.split(',').filter(id => id)
                this.models.projectMember = memberIds

                // 更新选中的成员姓名
                this.selectedMemberNames = memberIds.map(id => {
                  const user = this.allUsers.find(u => String(u.id) === String(id))
                  return user ? user.name : ''
                }).filter(name => name)

                // 更新显示文本
                this.selectedMemberText = this.selectedMemberNames.join('、')
                
                console.log('设置的项目成员:', {
                  ids: this.models.projectMember,
                  names: this.selectedMemberNames
                })
              } catch (err) {
                console.error('处理项目成员数据失败:', err)
                this.models.projectMember = []
                this.selectedMemberNames = []
                this.selectedMemberText = ''
              }
            }
          }

          // 显示对话框
          this.dialogVisible = true

          // 在下一个 tick 清除表单验证
          this.$nextTick(() => {
            if (this.$refs['generateForm']) {
              this.$refs['generateForm'].clearValidate()
            }
          })
        }).catch(err => {
          console.error('初始化数据失败:', err)
          this.$message.error('初始化数据失败，请刷新页面重试')
          this.dialogVisible = false
        })
      } catch (err) {
        console.error('open方法执行出错:', err)
        this.$message.error('打开编辑对话框失败，请刷新页面重试')
        this.dialogVisible = false
      }
    },
    resetData() {
      this.models = {
        projectMember: [],
        applyUserName: '',
        workNumber: '',
        fillTime: moment().format('YYYY-MM-DD HH:mm:ss'),
        name: '',
        projectNo: '',
        projectClass: '',
        applyDeptId: '',
        techType: '',
        applyManagerName: '',
        projectManagerContact: '',
        targetNumber: '',
        deviceNames: '',
        applyDocs: '',
        additionalDocs: ''
      }
      this.allUsers = []
      this.displayUserGroups = []
      this.departmentUserOptions = []
      this.selectedMemberNames = []
      this.selectedMemberText = ''
      this.techTypeArr = []
      this.memberDialogVisible = false
      
      // 清除可能的验证状态
      if (this.$refs['generateForm']) {
        this.$refs['generateForm'].clearValidate()
      }
    },
    handleLeader() {
      this.$refs.leaderRef.handleInversion()
    },
    getProcessNodeList() {
      processStructure({
        processId: 67
      }).then(response => {
        this.processStructureValue = response.data
        this.currentNode = this.processStructureValue.nodes[0]
        this.processStructureValue.tpls[0].form_structure.list[1].options.disabled = true
      })
    },
    draftAction() {
      if (this.workOrdeInfo.id) {
        this.models.id = this.workOrdeInfo.id
      }
      if(this.techTypeArr){
        this.models.techType = this.techTypeArr.join(',')
      }
      if(this.models.projectMember){
        this.models.projectMember = this.models.projectMember.join(',')
      }
      newCreateWorkOrder(this.models).then((res) => {
        // this.selectLeader(111111)
        this.$message({
          type: 'success',
          message: '暂存成功!'
        })
        if (!this.workOrdeInfo.id) {
          this.$router.push({
            path: '/xjsxxm/apply/myDraft',
            query: {
              id: res.records[0].id
            }
          })
        }
      })
    },
    submitAction() {
      if (this.workOrdeInfo.id) {
        this.models.id = this.workOrdeInfo.id
      }
      if(this.techTypeArr){
        this.models.techType = this.techTypeArr.join(',')
      }
      if(this.models.projectMember){
        this.models.projectMember = this.models.projectMember.join(',')
      }
      newCreateWorkOrder(this.models).then((res) => {
        if (this.workOrdeInfo.id) {
          newDoUpdate({ id: this.workOrdeInfo.id }).then(res => {
            console.log('提交', res)

            this.$message({
              type: 'success',
              message: '提交成功!'
            })
            // this.auditStatus = 2
            this.submitDisabled = false
            this.$router.push({ path: '/xjsxxm/apply/myApply' })
          })
        } else {
          const id = res.records[0].id
          newDoUpdate({ id }).then(res => {
            console.log('提交', res)

            this.$message({
              type: 'success',
              message: '提交成功!'
            })
            // this.auditStatus = 2
            this.submitDisabled = false
            this.$router.push({ path: '/xjsxxm/apply/myApply' })
          })
        }
      })
    },

    selectLeader(userId) {
      this.ruleForm.state[0]['processor'] = [userId]
      if (this.ruleForm.workOrderId > 0) {
        updateWorkOrder(this.ruleForm)
          .then(response => {
            if (response.code === 200) {
              this.$message({
                type: 'success',
                message: '提交成功!'
              })
              this.workOrdeInfo = response.data.workOrder
              this.ruleForm.workOrderId = this.workOrdeInfo.id
              this.recallStatus = 0
              this.$router.push({ path: '/project/applyList' })
              // this.$router.push({ path: "/process/upcoming" });
            }
          })
          .catch(() => {
            this.submitDisabled = false
          })
      } else {
        createWorkOrder(this.ruleForm)
          .then(response => {
            if (response.code === 200) {
              this.$message({
                type: 'success',
                message: '提交成功!'
              })
              this.workOrdeInfo = response.data.workOrder
              this.ruleForm.workOrderId = this.workOrdeInfo.id
              this.recallStatus = 0
              this.$router.push({ path: '/project/applyList' })
              // this.$router.push({ path: "/process/upcoming" });
            }
          })
          .catch(() => {
            this.submitDisabled = false
          })
      }
    },
    recallOrder() {
      this.recallDisabled = true
      const recallParams = {
        work_oroder_id: this.workOrdeInfo.id,
        process_id: this.workOrdeInfo.process
      }
      recallWorkOrder(recallParams)
        .then(response => {
          if (response.code === 200) {
            this.$message({
              type: 'success',
              message: '撤回成功!'
            })
            this.workOrdeInfo = response.data.workOrder
            this.ruleForm.workOrderId = this.workOrdeInfo.id
            this.recallDisabled = false
            this.recallStatus = 1
            // this.$router.push({ path: "/process/upcoming" });
          }
        })
        .catch(() => {
          this.recallDisabled = false
        })
    },
    // submitAction(item) {
    //   // console.log(232323,this.newUserInfo)

    //   this.$refs['generateForm'].validate(valid => {
    //     if (valid) {
    //       const loading = this.$loading({
    //         lock: true,
    //         text: 'Loading',
    //         spinner: 'el-icon-loading',
    //         background: 'rgba(0, 0, 0, 0.7)'
    //       })
    //       if (this.workOrdeInfo.id) {
    //         newDoUpdate({ id: this.workOrdeInfo.id }).then(res => {
    //           console.log('提交', res)

    //           this.$message({
    //             type: 'success',
    //             message: '提交成功!'
    //           })
    //           // this.auditStatus = 2
    //           this.submitDisabled = false
    //           loading.close()
    //           this.$router.push({ path: '/xjsxxm/apply/myApply' })
    //         })
    //       } else {
    //         newCreateWorkOrder(this.models).then((res) => {
    //           if(this.techTypeArr){
    //             this.models.techType = this.techTypeArr.join(',')
    //           }
    //           const id = res.records[0].id
    //           newDoUpdate({ id }).then(res => {
    //             console.log('提交', res)

    //             this.$message({
    //               type: 'success',
    //               message: '提交成功!'
    //             })
    //             // this.auditStatus = 2
    //             this.submitDisabled = false
    //             this.$router.push({ path: '/xjsxxm/apply/myApply' })
    //             loading.close()
    //           })
    //         })
    //       }
    //     }
    //   })
    //   // this.models.applyUserName = this.newUserInfo.name
    //   // this.models.workNumber   = this.newUserInfo.empNo

    //   /* this.$refs['ruleForm'].validate(valid => {
    //     if (valid) {
    //       this.submitDisabled = true
    //       var stateMap = {}
    //       this.ruleForm.process = 67
    //       this.ruleForm.status = 0
    //       this.ruleForm.classify = this.processStructureValue.process.classify
    //       stateMap['id'] = item.target
    //       this.ruleForm.source_state = this.processStructureValue.nodes[
    //         this.active
    //       ].label
    //       for (var v of this.processStructureValue.nodes) {
    //         if (v.id === item.target) {
    //           if (v.assignType !== undefined) {
    //             stateMap['process_method'] = v.assignType
    //           }
    //           if (v.assignValue !== undefined) {
    //             stateMap['processor'] = Array.from(new Set(v.assignValue))
    //           }
    //           stateMap['label'] = v.label
    //           stateMap['desc'] = v.desc
    //           break
    //         }
    //       }
    //       this.ruleForm.state = [stateMap]

    //       this.ruleForm.tpls = {
    //         form_name: [],
    //         form_structure: [],
    //         form_data: []
    //       }

    //       var promiseList = []

    //       this.tpls = []
    //       for (var tpl of this.newTpls) {
    //         this.tpls.push({
    //           tplDataId: tpl.id,
    //           tplId: tpl.form_structure.id
    //         })
    //       }

    //       for (var tpl of this.processStructureValue.tpls) {
    //         tpl.form_structure.id = tpl.id
    //         this.ruleForm.tpls.form_structure.push(tpl.form_structure)
    //         this.ruleForm.tpls.form_name.push(tpl.name)
    //         promiseList.push(this.$refs['generateForm-' + tpl.id][0].getData())
    //       }
    //       Promise.all(promiseList)
    //         .then(values => {
    //           this.ruleForm.source = this.processStructureValue.nodes[
    //             this.active
    //           ].id
    //           // console.log(values);
    //           let leadId = 0
    //           for (var item of values) {
    //             if (item.hasOwnProperty('project_name')) {
    //               this.ruleForm.title = item.project_name
    //             }
    //             if (item.hasOwnProperty('leader_name')) {
    //               leadId = item.leader_name
    //             }
    //           }
    //           if (this.tpls.length > 0) {
    //             for (var tplDataIndex in this.tpls) {
    //               this.tpls[tplDataIndex].tplValue = values[tplDataIndex]
    //             }
    //             this.ruleForm.newTpls = this.tpls
    //           }
    //           this.ruleForm.tpls.form_data = values
    //           this.ruleForm.is_exec_task = item.isExecuteTask

    //           // this.handleLeader();
    //           this.selectLeader(leadId)
    //           this.submitDisabled = false
    //         })
    //         .catch(() => {
    //           this.submitDisabled = false
    //         })
    //     }
    //   })*/
    // }
    openMemberDialog() {
      // 保存当前的选择状态
      this.originalSelectedMembers = [...this.models.projectMember]
      this.originalSelectedNames = [...this.selectedMemberNames]
      
      // 初始化临时选择状态
      this.tempSelectedMembers = [...this.models.projectMember]
      this.tempSelectedNames = [...this.selectedMemberNames]
      
      this.memberDialogVisible = true
      
      // 在下一个 tick 设置树的选中状态
      this.$nextTick(() => {
        if (this.$refs.memberTree) {
          // 先清空所有选中状态
          this.$refs.memberTree.setCheckedKeys([])
          // 设置原始选中状态
          this.originalSelectedMembers.forEach(id => {
            this.$refs.memberTree.setChecked(id, true, false)
          })
        }
      })
    },

    // 搜索过滤方法
    filterNode(value, data) {
      if (!value) return true
      return data.name.toLowerCase().indexOf(value.toLowerCase()) !== -1 ||
             (data.empNo && data.empNo.toLowerCase().indexOf(value.toLowerCase()) !== -1)
    },

    // 处理搜索输入
    handleSearch(value) {
      this.$refs.memberTree.filter(value)
    },

    // 处理树形选择
    handleTreeCheck(data, checked) {
      const checkedNodes = this.$refs.memberTree.getCheckedNodes()
      // 过滤出用户节点（有empNo的节点）
      const selectedUsers = checkedNodes.filter(node => node.empNo)
      
      this.tempSelectedMembers = selectedUsers.map(user => user.id.toString())
      this.tempSelectedNames = selectedUsers.map(user => user.name)
    },

    // 取消选择
    cancelMemberSelect() {
      // 恢复到原始选择状态
      this.models.projectMember = [...this.originalSelectedMembers]
      this.selectedMemberNames = [...this.originalSelectedNames]
      this.selectedMemberText = this.originalSelectedNames.join('、')
      
      // 关闭对话框
      this.memberDialogVisible = false
      
      // 重置临时存储的数据
      this.tempSelectedMembers = []
      this.tempSelectedNames = []
      this.searchKeyword = ''
    },

    // 确认选择
    confirmMemberSelect() {
      // 更新选择结果
      this.models.projectMember = [...this.tempSelectedMembers]
      this.selectedMemberNames = [...this.tempSelectedNames]
      this.selectedMemberText = this.selectedMemberNames.join('、')
      
      // 关闭对话框
      this.memberDialogVisible = false
      
      // 重置临时数据
      this.tempSelectedMembers = []
      this.tempSelectedNames = []
      this.searchKeyword = ''
    }
  },
  watch: {
    selectedMemberNames: {
      immediate: true,
      handler(val) {
        try {
          this.selectedMemberText = Array.isArray(val) ? val.join('、') : ''
        } catch (err) {
          console.error('更新选中成员文本失败:', err)
          this.selectedMemberText = ''
        }
      }
    },
    
    memberDialogVisible(newVal) {
      if (!newVal) {
        this.searchKeyword = ''
      }
    },

    // 监听路由变化
    '$route'(to, from) {
      if (to.path !== from.path) {
        this.resetData()
      }
    }
  },
  beforeDestroy() {
    this.resetData()
  },
  beforeRouteLeave(to, from, next) {
    this.resetData()
    next()
  }
}
</script>

<style lang="scss" scoped>
/* 去掉全选按钮 */
::v-deep .el-table .disabledCheck .cell .el-checkbox__inner {
    display: none !important;
}

::v-deep .el-table .disabledCheck .cell::before {
    content: "请选择";
    text-align: center;
    line-height: 37px;
}
.app-container {
    max-width: 1530px;
    margin: 0 auto;
    background: #ebf4fa;
    border-radius: 12px;
    .apply-box {
        border-radius: 15px;
        .line {
            height: 22px;
            width: 5px;
            background: #277fd6;
        }
    }
}

/* 选中成员样式 */
.selected-members {
  margin-top: 10px;
  
  .selected-title {
    font-size: 14px;
    color: #606266;
    margin-bottom: 5px;
  }
  
  .selected-names {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
    
    .member-tag {
      margin-right: 5px;
      margin-bottom: 5px;
    }
  }
}

/* 成员选择对话框样式 */
.member-dialog-content {
  .search-box {
    margin-bottom: 15px;
    
    .el-input {
      width: 100%;
    }
  }

  .tree-container {
    height: 400px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 10px;
    overflow-y: auto;
  }
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;

  span:last-child {
    color: #909399;
    font-size: 12px;
  }
}
</style>

